
    let eventId = window.location.pathname.split('/').pop();
    let eventDetail = null;
    let availableHandlers = /*[[${availableHandlers}]]*/ [];
    let assignedUnits = [];
    let availableResources = /*[[${availableResources}]]*/ [];
    let progressHistory = [];
    let resourceHistory = [];

    // JWT认证检查
    const checkAuth = () => {
        console.log('dispatch-event-detail.html: 开始认证检查');
        
        if (!window.AuthManager || !AuthManager.isAuthenticated()) {
            console.log('用户未认证，重定向到登录页');
            AuthManager.redirectToLogin();
                return;
            }
        
        // 检查token有效性
        AuthManager.verifyToken()
            .then(() => {
                console.log('Token验证成功，初始化页面');
                
                // 显示用户信息
                displayUserInfo();
                
            initPage();
            })
            .catch(error => {
                console.error('Token验证失败:', error);
                AuthManager.redirectToLogin();
            });
    };
    document.addEventListener('DOMContentLoaded', checkAuth);

    // 显示用户信息
    function displayUserInfo() {
        const userInfo = AuthManager.getUserInfo();
        if (userInfo && userInfo.realName) {
            document.getElementById('userRealName').textContent = userInfo.realName;
        }
    }

    function initPage() {
        loadEventDetail();
        loadUsers();
        loadResources();
        setInterval(function() {
            loadEventDetail();
        }, 5000);
        renderHandlers();
        renderAvailableResources();
        renderAssignedUnits();
        document.getElementById('assignHandlerAndResourceForm').addEventListener('submit', assignHandlerAndResources);
        document.getElementById('progressForm').addEventListener('submit', updateProgress);
    }

    async function loadEventDetail() {
        const headers = {};
        if (window.AuthManager && window.AuthManager.getAuthHeaders) {
            Object.assign(headers, window.AuthManager.getAuthHeaders());
        }
        
        const res = await fetch(`/ercms/dispatch/api/events/${eventId}`, {
            headers: headers
        });
        const result = await res.json();
        if (result.success) {
            eventDetail = result.data;
            progressHistory = result.progressHistory || [];
            resourceHistory = result.resourceHistory || [];
            assignedUnits = result.assignedUnits || [];
            renderEventDetail();
            renderProgressHistory();
            renderResourceHistory();
            renderTimeline();
            renderAssignedUnits();
            if (!eventDetail.acceptedTime && eventDetail.responderStatus && ['ACCEPTED', 'EN_ROUTE', 'ARRIVED', 'IN_PROGRESS', 'COMPLETED', 'RETURNING'].includes(eventDetail.responderStatus)) {
                try {
                    const timelineRes = await fetch(`/ercms/api/events/${eventId}/timeline`, {
                        headers: headers
                    });
                    if (timelineRes.ok) {
                        const timelineData = await timelineRes.json();
                        const acceptedItem = timelineData.find(item => item.type === 'TASK_ACCEPTED');
                        if (acceptedItem) {
                            // ...
                        }
                    }
                } catch (error) {
                    console.log('获取后端时间线失败', error);
                }
            }
            if (eventDetail.status === 'RESOLVED' || eventDetail.status === 'CLOSED') {
                document.getElementById('assignedUnitsCard').style.display = 'none';
                document.getElementById('assignHandlerAndResourceCard').style.display = 'none';
            } else {
                document.getElementById('assignedUnitsCard').style.display = '';
                document.getElementById('assignHandlerAndResourceCard').style.display = '';
            }
            if (window.renderEventMap) renderEventMap();
        } else {
            alert('加载事件详情失败: ' + result.message);
        }
    }

    function renderEventDetail() {
        document.getElementById('eventId').textContent = eventDetail.id;
        document.getElementById('eventTitle').textContent = eventDetail.title;
        document.getElementById('eventType').textContent = eventDetail.eventType ? eventDetail.eventType.name : '';
        document.getElementById('eventDescription').textContent = eventDetail.description;
        document.getElementById('eventPriority').textContent = getPriorityText(eventDetail.priority);
        document.getElementById('eventSeverity').textContent = getSeverityText(eventDetail.severity);
        document.getElementById('eventStatus').textContent = getStatusText(eventDetail.status);
        document.getElementById('eventStatus').className = 'badge badge-status bg-' + getStatusColor(eventDetail.status);
        document.getElementById('eventSafetyStatus').textContent = getSafetyStatusText(eventDetail.safetyStatus);
        document.getElementById('eventSafetyStatus').className = 'badge badge-status bg-' + getSafetyStatusColor(eventDetail.safetyStatus);
        document.getElementById('eventSupportRequest').textContent = getSupportRequestText(eventDetail.supportRequested);
        document.getElementById('eventSupportRequest').className = 'badge badge-status bg-' + getSupportRequestColor(eventDetail.supportRequested);
        document.getElementById('eventReporter').textContent = eventDetail.reporter ? eventDetail.reporter.realName : '';
        document.getElementById('eventTime').textContent = formatDateTime(eventDetail.startTime);
        renderAssignedUnits();
        renderHandlers();
        renderAvailableResources();
    }

    function renderAssignedUnits() {
        const unitList = document.getElementById('assignedUnitsList');
        if (!assignedUnits || assignedUnits.length === 0) {
            unitList.innerHTML = '<li class="list-group-item">暂无指派单位</li>';
            return;
        }
        unitList.innerHTML = assignedUnits
            .filter(unit => unit.handler || unit.resource)
            .map(unit => {
                const handler = unit.handler ? `<i class='bi bi-person'></i> ${unit.handler.realName}（${unit.handler.username}）` : '<span class="text-muted">无</span>';
                const resource = unit.resource ? `<i class='bi bi-truck'></i> ${unit.resource.name}` : '<span class="text-muted">无</span>';
                return `<li class="list-group-item d-flex justify-content-between align-items-center">
                    <span>${handler} + ${resource}</span>
                </li>`;
            }).join('');
    }

    function renderAvailableResources() {
        const select = document.getElementById('resourceSelect');
        if (!availableResources || availableResources.length === 0) {
            select.innerHTML = '<option value="">暂无可用单位</option>';
            return;
        }
        select.innerHTML = '<option value="">请选择单位</option>' + availableResources.map(res =>
            `<option value="${res.id}">${res.name}</option>`
        ).join('');
    }

    function renderHandlers() {
        const select = document.getElementById('handlerSelect');
        select.innerHTML = '<option value="">请选择处理人</option>' + availableHandlers.map(u => {
            const roleText = getRoleDisplayName(u.role);
            const statusText = getStatusDisplayName(u.status);
            return `<option value="${u.id}">${u.realName}（${u.username}） - ${roleText} - ${statusText}</option>`;
        }).join('');
        if (eventDetail && eventDetail.handler) {
            select.value = eventDetail.handler.id;
        }
    }

    function getRoleDisplayName(role) {
        const roleNames = {
            'ADMIN': '系统管理员',
            'DEPT_MANAGER': '部门管理员',
            'DISPATCHER': '调度员',
            'END_USER': '终端用户'
        };
        return roleNames[role] || role;
    }

    function getStatusDisplayName(status) {
        const statusNames = {
            'AVAILABLE': '可用',
            'BUSY': '忙碌',
            'OFFLINE': '离线'
        };
        return statusNames[status] || status;
    }

    async function assignHandlerAndResources(e) {
        e.preventDefault();
        const handlerId = document.getElementById('handlerSelect').value;
        const resourceId = document.getElementById('resourceSelect').value;
        if (!handlerId && !resourceId) {
            alert('请选择处理人和单位');
            return;
        }
        
        const headers = {};
        if (window.AuthManager && window.AuthManager.getAuthHeaders) {
            Object.assign(headers, window.AuthManager.getAuthHeaders());
        }
        
        try {
            if (handlerId) {
                const res1 = await fetch(`/ercms/dispatch/api/events/${eventId}/assign-handler`, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({ handlerId: parseInt(handlerId) })
                });
                const result1 = await res1.json();
                if (!result1.success) {
                    alert('处理人指派失败：' + result1.message);
                    return;
                }
            }
            if (resourceId) {
                const res2 = await fetch(`/ercms/dispatch/api/events/${eventId}/assign-resources`, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({ resourceIds: [parseInt(resourceId)] })
                });
                const result2 = await res2.json();
                if (!result2.success) {
                    alert('单位指派失败：' + result2.message);
                    return;
                }
            }
            alert('指派成功！');
            location.reload();
        } catch (error) {
            console.error('指派失败:', error);
            alert('指派失败，请检查网络连接');
        }
    }

    async function updateProgress(e) {
        e.preventDefault();
        const progress = document.getElementById('progressInput').value;
        const status = document.getElementById('statusInput').value;
        if (!progress.trim()) {
            alert('请填写进度描述');
            return;
        }
        
        const headers = {};
        if (window.AuthManager && window.AuthManager.getAuthHeaders) {
            Object.assign(headers, window.AuthManager.getAuthHeaders());
        }
        
        const res = await fetch(`/ercms/dispatch/api/events/${eventId}/progress`, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ progress, status })
        });
        const result = await res.json();
        if (result.success) {
            alert('进度已更新！');
            document.getElementById('progressInput').value = '';
            loadEventDetail();
        } else {
            alert('进度更新失败: ' + result.message);
        }
    }

    function renderProgressHistory() {
        const container = document.getElementById('progressHistoryList');
        if (progressHistory && progressHistory.length > 0) {
            container.innerHTML = progressHistory.map(p => {
                let locationInfo = '';
                if (p.location) {
                    locationInfo = `<br><small class="text-info"><i class="bi bi-geo-alt"></i> 响应位置: ${p.location}</small>`;
                }
                return `
                    <div class="mb-2">
                        <span class="badge bg-secondary">${formatDateTime(p.responseTime)}</span>
                        <span class="ms-2">${p.description}</span>
                        <span class="ms-2 text-muted">${getStatusText(p.status)}</span>
                        ${locationInfo}
                    </div>
                `;
            }).join('');
        } else {
            container.innerHTML = '暂无进度记录';
        }
    }

    function renderResourceHistory() {
        const container = document.getElementById('resourceHistoryList');
        if (resourceHistory && resourceHistory.length > 0) {
            container.innerHTML = resourceHistory.map(h => `
                <div class="mb-2 border-bottom pb-2">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <strong><i class="bi bi-truck"></i> ${h.resource ? h.resource.name : '未知资源'}</strong>
                            <br>
                            <small class="text-muted">状态 ${getResourceStatusText(h.status)}</small>
                        </div>
                        <small class="text-muted">${formatDateTime(h.assignedAt)}</small>
                    </div>
                    ${h.notes ? `<div class="mt-1"><small class="text-info">${h.notes}</small></div>` : ''}
                </div>
            `).join('');
        } else {
            container.innerHTML = '暂无调配记录';
        }
    }

    function getResourceStatusText(status) {
        const statusTexts = {
            'ASSIGNED': '已指派',
            'IN_USE': '使用中',
            'COMPLETED': '已完成',
            'AVAILABLE': '可用'
        };
        return statusTexts[status] || status;
    }

    function renderTimeline() {
        const list = document.getElementById('timelineList');
        if (!eventDetail) return;
        let items = [];
        if (eventDetail.startTime) items.push({ time: eventDetail.startTime, text: '事件创建' });
        if (eventDetail.assignedTime) items.push({ time: eventDetail.assignedTime, text: getStatusText('ASSIGNED') });
        
        // 检查是否已接受 - 优先使用时间戳，如果没有时间戳但状态是已接受，则使用当前时间
        if (eventDetail.acceptedTime) {
            items.push({ time: eventDetail.acceptedTime, text: getStatusText('ACCEPTED') });
        } else if (eventDetail.responderStatus && ['ACCEPTED', 'EN_ROUTE', 'ARRIVED', 'IN_PROGRESS', 'COMPLETED', 'RETURNING'].includes(eventDetail.responderStatus)) {
            // 如果状态显示已接受或更高状态，但没有时间戳，说明已接受但时间戳丢失
            items.push({ time: eventDetail.assignedTime || eventDetail.startTime, text: getStatusText('ACCEPTED') + ' (时间戳缺失)' });
        }
        
        if (eventDetail.enRouteTime) items.push({ time: eventDetail.enRouteTime, text: getStatusText('EN_ROUTE') });
        if (eventDetail.arrivedTime) items.push({ time: eventDetail.arrivedTime, text: getStatusText('ARRIVED') });
        if (eventDetail.inProgressTime) items.push({ time: eventDetail.inProgressTime, text: getStatusText('IN_PROGRESS') });
        if (eventDetail.completedTime) items.push({ time: eventDetail.completedTime, text: getStatusText('COMPLETED') });
        if (eventDetail.returningTime) items.push({ time: eventDetail.returningTime, text: getStatusText('RETURNING') });
        if (eventDetail.resolutionTime) items.push({ time: eventDetail.resolutionTime, text: getStatusText('RESOLVED') });
        if (eventDetail.status === 'CLOSED' && eventDetail.resolutionTime) items.push({ time: eventDetail.resolutionTime, text: getStatusText('CLOSED') });
        
        // 添加调试信息
        console.log('事件详情:', eventDetail);
        console.log('事件状态:', eventDetail.status);
        console.log('响应者状态:', eventDetail.responderStatus);
        console.log('已接受时间:', eventDetail.acceptedTime);
        console.log('已指派时间:', eventDetail.assignedTime);
        console.log('开始处理时间:', eventDetail.inProgressTime);
        console.log('解决时间:', eventDetail.resolutionTime);
        console.log('时间线项:', items);
        
        list.innerHTML = items.map(i => `<li class="list-group-item"><span class="badge bg-info">${formatDateTime(i.time)}</span> ${i.text}</li>`).join('');
    }

    function getPriorityText(priority) {
        return { 'HIGH': '高', 'MEDIUM': '中', 'LOW': '低' }[priority] || priority;
    }

    function getSeverityText(severity) {
        return { 'CRITICAL': '严重', 'SEVERE': '严重', 'HIGH': '高', 'MODERATE': '中', 'MEDIUM': '中', 'MINOR': '轻微', 'LOW': '低' }[severity] || severity;
    }

    function getStatusText(status) {
        const texts = {
            'PENDING': '待处理',
            'ASSIGNED': '已指派',
            'ACCEPTED': '已接受',
            'EN_ROUTE': '正在前往',
            'ARRIVED': '到达现场',
            'IN_PROGRESS': '开始处理',
            'COMPLETED': '完成任务',
            'RETURNING': '正在返程',
            'RESOLVED': '已解决',
            'CLOSED': '已关闭'
        };
        return texts[status] || status;
    }

    function getStatusColor(status) {
        const colors = {
            'PENDING': 'warning',
            'ASSIGNED': 'info',
            'ACCEPTED': 'primary',
            'EN_ROUTE': 'primary',
            'ARRIVED': 'primary',
            'IN_PROGRESS': 'primary',
            'COMPLETED': 'success',
            'RETURNING': 'success',
            'RESOLVED': 'success',
            'CLOSED': 'secondary'
        };
        return colors[status] || 'secondary';
    }

    function getSafetyStatusText(status) {
        const texts = {
            'SAFE': '安全',
            'CAUTION': '注意',
            'DANGER': '危险',
            'SOS': '紧急求助'
        };
        return texts[status] || (status || '未知');
    }

    function getSafetyStatusColor(status) {
        const colors = {
            'SAFE': 'success',
            'CAUTION': 'warning',
            'DANGER': 'danger',
            'SOS': 'danger'
        };
        return colors[status] || 'secondary';
    }

    function getSupportRequestText(supportRequested) {
        if (!supportRequested) {
            return '无';
        }
        return '已请求';
    }

    function getSupportRequestColor(supportRequested) {
        return supportRequested ? 'warning' : 'secondary';
    }

    function formatDateTime(dateTime) {
        if (!dateTime) return '';
        const date = new Date(dateTime);
        return date.toLocaleString('zh-CN');
    }

    window.removeResource = async function(resourceId) {
        if (!confirm('确定要移除此单位的指派吗？')) return;
        
        const headers = {};
        if (window.AuthManager && window.AuthManager.getAuthHeaders) {
            Object.assign(headers, window.AuthManager.getAuthHeaders());
        }
        
        const res = await fetch(`/ercms/dispatch/api/events/${eventId}/remove-resource`, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ resourceId })
        });
        const result = await res.json();
        if (result.success) {
            alert('移除成功！');
            loadEventDetail();
        } else {
            alert('移除失败: ' + result.message);
        }
    };

    // 加载用户列表
    async function loadUsers() {
        try {
            const headers = {};
            if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                Object.assign(headers, window.AuthManager.getAuthHeaders());
            }
            
            const response = await fetch('/ercms/api/users', {
                headers: headers
            });
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    availableHandlers = result.data.filter(user => 
                        user.status === 'AVAILABLE' && 
                        ['ADMIN', 'DISPATCHER', 'END_USER'].includes(user.role)
                    );
                    renderHandlers();
                }
            }
        } catch (error) {
            console.error('加载用户失败:', error);
        }
    }

    // 加载资源列表
    async function loadResources() {
        try {
            const headers = {};
            if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                Object.assign(headers, window.AuthManager.getAuthHeaders());
            }
            
            const response = await fetch('/ercms/api/resources', {
                headers: headers
            });
            if (response.ok) {
                const result = await response.json();
                if (result.success) {
                    availableResources = result.data.filter(resource => 
                        resource.status === 'AVAILABLE'
                    );
                    renderAvailableResources();
                }
            }
        } catch (error) {
            console.error('加载资源失败:', error);
        }
    }

function renderEventMap() {
    if (!eventDetail) return;
    
    // 事件位置 - 使用Event.location字段
    let eventLat = null;
    let eventLng = null;
    if (eventDetail.location && eventDetail.location.includes(',')) {
        const parts = eventDetail.location.split(',');
        if (parts.length === 2) {
            eventLng = Number(parts[0].trim());
            eventLat = Number(parts[1].trim());
        }
    }
    
    if (isNaN(eventLat) || isNaN(eventLng)) {
        document.getElementById('eventMap').innerHTML = '<div class="text-muted text-center pt-5">暂无事件定位信息</div>';
        document.getElementById('eventLocation').textContent = '暂无事件定位信息';
        console.debug('地图渲染: 无有效事件坐标');
        return;
    }
    
    console.debug('地图渲染: 事件坐标', {eventLng, eventLat});
    const map = new AMap.Map('eventMap', {
        zoom: 16,
        center: [eventLng, eventLat],
        viewMode: '3D'
    });
    
    // 事件位置标记（红色）
    const eventMarker = new AMap.Marker({
        position: new AMap.LngLat(eventLng, eventLat),
        map: map,
        title: '事件位置',
        icon: new AMap.Icon({
            size: new AMap.Size(32, 32),
            image: ''
        })
    });
    
    // 异步获取最新响应者位置并显示
    loadAllResponderLocations(eventDetail.id, map, eventLat, eventLng);
    
    const infoWindow = new AMap.InfoWindow({
        anchor: 'top-center'
    });

    // 异步加载逆地理编码插件
    AMap.plugin('AMap.Geocoder', function() {
        const geocoder = new AMap.Geocoder({
            city: "全国" // "全国"表示全国范围内的逆地理编码
        });
        geocoder.getAddress([eventLng, eventLat], function(status, result) {
            let address = `${eventLng},${eventLat}`; // Fallback to coordinates
            if (status === 'complete' && result.regeocode) {
                address = result.regeocode.formattedAddress;
                console.debug('逆地理编码成功', address);
            } else {
                console.error('逆地理编码失败', result);
            }
            // 赋值地名到文字行和地图弹窗
            document.getElementById('eventLocation').textContent = address;
            infoWindow.setContent(`
                <div style="padding: 8px;">
                    <h6>事件位置</h6>
                    <p>${address}</p>
                </div>
            `);
            // 自动弹出信息窗体
            infoWindow.open(map, eventMarker.getPosition());
        });
    });

    // 点击标记点时，再次打开信息窗体
    eventMarker.on('click', function() {
        infoWindow.open(map, eventMarker.getPosition());
    });
}

// 加载所有响应者位置
async function loadAllResponderLocations(eventId, map, eventLat, eventLng) {
    try {
        const headers = {};
        if (window.AuthManager && window.AuthManager.getAuthHeaders) {
            Object.assign(headers, window.AuthManager.getAuthHeaders());
        }
        
        const response = await fetch(`/ercms/api/events/${eventId}/all-responder-locations`, {
            headers: headers
        });
        
        if (response.ok) {
            const result = await response.json();
            if (result.success && result.data) {
                const responderLocations = result.data;
                if (responderLocations && responderLocations.length > 0) {
                    responderLocations.forEach(locationInfo => {
                        if (locationInfo.location && locationInfo.location.includes(',')) {
                            const parts = locationInfo.location.split(',');
                            if (parts.length === 2) {
                                const responderLng = Number(parts[0].trim());
                                const responderLat = Number(parts[1].trim());
                                
                                if (!isNaN(responderLat) && !isNaN(responderLng) &&
                                    (Math.abs(responderLat - eventLat) > 0.0001 || Math.abs(responderLng - eventLng) > 0.0001)) {
                                    
                                    // 响应者位置标记（蓝色）
                                    const responderMarker = new AMap.Marker({
                                        position: new AMap.LngLat(responderLng, responderLat),
                                        map: map,
                                        title: `${locationInfo.responderName}的位置`,
                                        icon: new AMap.Icon({
                                            size: new AMap.Size(28, 28),
                                            image: ''
                                        })
                                    });
                                    
                                    // 响应者位置信息窗体
                                    const responderInfoWindow = new AMap.InfoWindow({
                                        content: `
                                            <div style="padding: 8px;">
                                                <h6>${locationInfo.responderName}的位置</h6>
                                                <p>用户名: ${locationInfo.responderUsername}</p>
                                                <p>坐标: ${responderLng.toFixed(4)}, ${responderLat.toFixed(4)}</p>
                                                <p>更新时间: ${new Date(locationInfo.updateTime).toLocaleString('zh-CN')}</p>
                                            </div>
                                        `
                                    });
                                    
                                    responderMarker.on('click', function() {
                                        responderInfoWindow.open(map, responderMarker.getPosition());
                                    });
                                }
                            }
                        }
                    });
                }
            }
        }
    } catch (error) {
        console.error('获取响应者位置失败:', error);
    }
}
